﻿using System;
using System.IO;
using System.Linq;

namespace IcqSharp
{
    public static class Utilities
    {
        public static UInt16 GenerateFlapSequence()
        {
            var rand = new Random((Int32)DateTime.Now.Ticks);
            var n = (UInt16)(rand.Next() % 0xFFFF); var s = 0;

            for (UInt16 i = n; (i >>= 3) > 0; s += i) ;

            return (UInt16)((((0 - s) ^ (Byte)n) & 7 ^ n) + 2);
        }

        public static Boolean IsStringUIN(String s)
        {
            if (String.IsNullOrEmpty(s)) return false;
            if (s.StartsWith("0")) return false;
            if (s.Length > 11) return false;

            return s.Count(c => !Char.IsDigit(c)) == 0;
        }

        public static Boolean UnpackUID(MemoryStream stream, out UInt32 UIN, out String UID)
        {
            // default
            UIN = 0; UID = null;

            // length
            var len = (UInt16)stream.ReadByte();
            if (len == 0 || len > stream.Available()) 
                return false;

            // read
            var input = stream.ReadAsciiString(len);

            // write to UIN/UID
            if (Utilities.IsStringUIN(input))
                 UIN = UInt32.Parse(input);
            else UID = input; 
            
            return true;
        }



    }
}
